package com.dmm.user.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dmm.Exception.Exceptionbean;
import com.dmm.redis.redisService;
import com.dmm.result.Result;
import com.dmm.user.entity.Apply;
import com.dmm.user.entity.Association;
import com.dmm.user.entity.Examineinfo;
import com.dmm.user.entity.Question;
import com.dmm.user.service.AssociationService;
import com.dmm.user.service.ExamineinfoService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author com/dmm
 * @since 2023-04-07
 */
@RestController
@RequestMapping("/user/examineinfo")
@CrossOrigin
public class ExamineinfoController {


    @Autowired
    ExamineinfoService examineinfoService;

    @Autowired
    redisService redisService;

    @Autowired
    AssociationService associationService;



    @ApiOperation("添加考试信息")
    @PostMapping("/saveinfo")
    public Result saveinfo(@RequestBody Examineinfo examineinfo){
        QueryWrapper<Examineinfo> queryWrapper =new QueryWrapper<>();
        queryWrapper.eq("email",examineinfo.getEmail());
        int count = examineinfoService.count(queryWrapper);
        if(count==0){
            boolean save = examineinfoService.save(examineinfo);
            return Result.success(null);
        }else {
            throw new Exceptionbean(20001,"请不要重复报名");
        }
    }

    @ApiOperation("获取考生信息")
    @GetMapping("/getname/{email}")
    public Result getname(@PathVariable String email){

        QueryWrapper<Examineinfo> queryWrapper =new QueryWrapper<>();
        queryWrapper.eq("email",email);
        int count = examineinfoService.count(queryWrapper);
        if(count==0){
            throw new Exceptionbean(20001,"你还没进行报名，请先报名");
        }
        Examineinfo one = examineinfoService.getOne(queryWrapper);
        return Result.success(one);

    }

    @ApiOperation("获取number考试次数")
    @PutMapping("/getnumber/{email}")
    public Result getnumber(@PathVariable String email){
        QueryWrapper<Examineinfo> queryWrapper =new QueryWrapper<>();
        queryWrapper.eq("email",email);
        Examineinfo one = examineinfoService.getOne(queryWrapper);
        boolean bool=examineinfoService.updateNumber(email);
        return Result.success(one);

    }


    @ApiOperation("考核成绩")
    @PostMapping("saveresult/{textarea}/{email}")
    public Result saveresult( @PathVariable String textarea,
                              @PathVariable String email
                                , HttpServletRequest request){

        int temp=0;
        if(redisService.getKey(email + "question")){
            List<Question> list=new ArrayList<>();
            list = redisService.get(email + "question", Question.class);
            int a=list.size();
            redisService.delete(email + "question");
            System.out.println(textarea);
            String[] split = textarea.split(",");
            String email1 = request.getHeader("token");
            int i=0;
            int p=split.length;
            System.out.println(p);
            for(Question question : list){
                if(i<p){
                    if(split[i].equals("A")){
                        temp=temp+question.getSubjecta();
                    }else if(split[i].equals("B")){
                        temp=temp+question.getSubjectb();
                    }else if(split[i].equals("C")){
                        temp=temp+question.getSubjectc();
                    }else {
                        temp=temp+question.getSubjectd();
                    }
                    i++;
                }else  {
                    temp=temp+question.getSubjectd();
                }

            }
            System.out.println(temp);
            //题数
            System.out.println(a);
            temp=temp/(a*10);
            //将这次打分计入关联表中
            associationService.addform(email1,email);
            //查询多少个人给打过分
            QueryWrapper<Association> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("start_email",email);
            int count = associationService.count(queryWrapper);
            //查询北大分人信息
            QueryWrapper<Examineinfo> queryWrapper1=new QueryWrapper<>();
            queryWrapper1.eq("email",email);
            Examineinfo one = examineinfoService.getOne(queryWrapper1);
            one.setTotal(one.getTotal()+temp);

            one.setResult(one.getTotal()/count);
            //将分数加入
            examineinfoService.updateById(one);

        }else {
            throw new Exceptionbean(20001,"逗留时间太长请重新打分");
        }

        return Result.success(null);

    }

    @ApiOperation("获取考试成绩")
    @PostMapping("/getbyinfo/{email}")
    public Result getbyinfo(@PathVariable String email){

        QueryWrapper<Examineinfo> queryWrapper =new QueryWrapper<>();
        queryWrapper.eq("email",email);
        int count = examineinfoService.count(queryWrapper);
        List<Examineinfo> list =new ArrayList<>();
        Map<String,Object> map=new HashMap<>();
        map.put("step",1);
        if(count==0){
            map.put("step",1);
            map.put("list",list);
            return Result.success(map);
        }
        Examineinfo one = examineinfoService.getOne(queryWrapper);

        if(one.getResult()==0){
            list.add(one);
            map.put("step",2);
            map.put("list",list);
            return Result.success(map);

        }
        list.add(one);
        map.put("step",3);
        map.put("list",list);
        return Result.success(map);

    }

    @ApiOperation("分页查询")
    @PostMapping("list/{page}/{limit}")
    public Result index(
            @ApiParam(name = "page", value = "当前页码", required = true)
            @PathVariable Long page,
            @ApiParam(name = "limit", value = "每页记录数", required = true)
            @PathVariable Long limit,
            @ApiParam(name = "Examineinfo", value = "查询对象", required = false)
            // required = false传入参数可以为空
            @RequestBody(required = false) Examineinfo examineinfo) {
        //创建page对象，传递当前页和每页记录数
        Page<Examineinfo> pageParam = new Page<>(page, limit);
        //获取条件值
        String name = examineinfo.getName();//用户名
        String email = examineinfo.getEmail();//用户邮箱
        Integer lowest = examineinfo.getLowest();//最低分
        Integer maximum = examineinfo.getMaximum();//最高分
        //封装条件
        QueryWrapper<Examineinfo> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(name)) {
            wrapper.like("name",name);
        }
        if(!StringUtils.isEmpty(email)) {
            wrapper.eq("email",email);
        }
        if(!StringUtils.isEmpty(lowest)) {
            wrapper.ge("result",lowest);
        }
        if(!StringUtils.isEmpty(maximum)) {
            wrapper.le("result",maximum);
        }

        //调用方法得到分页查询结果
        IPage<Examineinfo> pageModel = examineinfoService.page(pageParam,wrapper);
        return Result.success(pageModel);
    }

    @ApiOperation("逻辑删除")
    @DeleteMapping("/deleteId/{id}")
    public Result deleteId(@PathVariable Long id){
        Examineinfo byId = examineinfoService.getById(id);
        boolean b = examineinfoService.removeById(id);

        QueryWrapper<Association> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("start_email",byId.getEmail());
        associationService.remove(queryWrapper);
        if(b){
            return Result.success(null);
        }
        return Result.fail(null);
    }

    @ApiOperation("批量删除")
    @DeleteMapping("/Batch_delete")
    public Result Batch_delete(@RequestBody List<Long> list){
        //先查询被删除的邮箱
        List<Examineinfo> list1=examineinfoService.getByIds(list);
        boolean b = examineinfoService.removeByIds(list);

        return b? Result.success(null):Result.fail(null);
    }

    @ApiOperation("根据email获取考生信息")
    @PutMapping("/getcandidate/{email}")
    public Result getcandidate(@PathVariable String email){

        QueryWrapper<Examineinfo> queryWrapper =new QueryWrapper<>();
        queryWrapper.eq("email",email);
        Examineinfo one = examineinfoService.getOne(queryWrapper);
        return Result.success(one);
    }

    @ApiOperation("根据id获取考生信息")
    @PutMapping("/getidbyinfo/{id}")
    public Result getidbyinfo(@PathVariable Long id){

        Examineinfo byId = examineinfoService.getById(id);

        return Result.success(byId);
    }

    @ApiOperation("根据id更新考生信息")
    @PostMapping("/updatecandidate")
    public Result updatecandidate(@RequestBody Examineinfo examineinfo){

        boolean b = examineinfoService.updateById(examineinfo);
        return Result.success(null);
    }

    @ApiOperation("绘图根据分数看人数")
    @GetMapping("/getquantity")
    public Result getquantity(){

        Map<String,Object> map=examineinfoService.getquantity();
        return Result.success(map);
    }

    @ApiOperation("绘图根据分数看人数")
    @GetMapping("/getavg")
    public Result getavg(){

        Map<String,Object> map=examineinfoService.getavg();
        return Result.success(map);
    }

    @ApiOperation("获取可以被打分的用户")
    @GetMapping("/getnames/{page}/{limit}/{email}")
    public Result getnames(  @ApiParam(name = "page", value = "当前页码", required = true)
                                 @PathVariable Long page,
                             @ApiParam(name = "limit", value = "每页记录数", required = true)
                                 @PathVariable Long limit,
                                 @PathVariable String email){

        List<String> list=examineinfoService.getnames(email);
        Page<Examineinfo> pageParam = new Page<>(page, limit);
        QueryWrapper<Examineinfo> queryWrapper =new QueryWrapper<>();
        queryWrapper.in("email",list);
        try {
            Page<Examineinfo> page1 = examineinfoService.page(pageParam, queryWrapper);
            return Result.success(page1);
        }catch (Exception e){
            return Result.success(null);
        }


    }



}

